package com.lxt.ScreencastGallery;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.media3.common.VideoSize;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.common.Player;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ThumbnailAdapter.OnItemClickListener {

    private RecyclerView thumbnailRecyclerView;
    private ZoomableImageView imageView;
    private DraggableVideoView videoView; // 修改为 DraggableVideoView
    private ProgressBar loadingIndicator;
    private FrameLayout displayArea;
    private TextView statusText;

    private EditText topMarginEdit;
    private EditText heightEdit;
    private EditText widthEdit;

    private ThumbnailAdapter thumbnailAdapter;
    private MediaManager mediaManager;
    private ExoPlayer exoPlayer; // 保持为 ExoPlayer 类型
    private Handler mainHandler;

    private List<MediaItem2> mediaItems;
    private MediaItem2 currentMediaItem;
    private static final int REQUEST_CODE_PERMISSIONS = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainHandler = new Handler(Looper.getMainLooper());

        initViews();
        initPlayer();
        checkAndRequestPermissions();
    }

    private void initViews() {
        thumbnailRecyclerView = findViewById(R.id.thumbnail_recycler_view);
        imageView = findViewById(R.id.image_view);
        videoView = findViewById(R.id.video_view); // 现在 videoView 是 DraggableVideoView 类型
        loadingIndicator = findViewById(R.id.loading_indicator);
        displayArea = findViewById(R.id.display_area);
        statusText = findViewById(R.id.status_text);
        widthEdit = findViewById(R.id.width_edit);

        TextView librarySelectorButton = findViewById(R.id.library_selector_button);



        topMarginEdit = findViewById(R.id.top_margin_edit);
        heightEdit = findViewById(R.id.height_edit);

        // 设置初始值
        SharedPreferences prefs = getSharedPreferences("display_config", MODE_PRIVATE);
        int topMargin = prefs.getInt("top_margin", AppConfig.DISPLAY_TOP_MARGIN);
        int height = prefs.getInt("height", AppConfig.DISPLAY_HEIGHT);
        int width = prefs.getInt("width", AppConfig.DISPLAY_WIDTH);

        // 如果是默认值0，则显示动态计算的值
        if (width == 0) {
            widthEdit.setHint(String.valueOf(getScreenWidth()));
            Log.d("widthEdit", "initViews: "+getScreenWidth());
        } else {
            widthEdit.setText(String.valueOf(width));
        }

        if (height == 0) {
            heightEdit.setHint(String.valueOf(calculateDisplayHeight()));
            Log.d("heightEdit", "initViews: "+calculateDisplayHeight());
        } else {
            heightEdit.setText(String.valueOf(height));
        }

        topMarginEdit.setText(String.valueOf(topMargin));

        // 限制输入范围不超过1000
        topMarginEdit.setFilters(new android.text.InputFilter[]{new MaxValueFilter(1000)});
        heightEdit.setFilters(new android.text.InputFilter[]{new MaxValueFilter(2000)});
//        widthEdit.setFilters(new android.text.InputFilter[]{new MaxValueFilter(2000)});


        // 设置编辑框监听器
        topMarginEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                saveDisplayConfig();
            }
        });

        heightEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                saveDisplayConfig();
            }
        });

        //宽度监听
        widthEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                saveDisplayConfig();
            }
        });

        // 设置显示区域的初始位置和尺寸
        adjustDisplayArea();

        // 设置缩略图列表为4列
        GridLayoutManager layoutManager = new GridLayoutManager(this, AppConfig.THUMBNAIL_COLUMNS);
        thumbnailRecyclerView.setLayoutManager(layoutManager);

        mediaManager = new MediaManager(this);

//        // 初始化图库选择
//        initializeLibrarySelector(librarySpinner);

        // 设置图库选择按钮点击事件
        librarySelectorButton.setOnClickListener(v -> showLibrarySelector());

        // 设置视频播放器 (修改这里)
        ExoPlayer player = new ExoPlayer.Builder(this).build();
        videoView.getPlayerView().setPlayer(player);

        // 监听视频尺寸变化 (修改这里)
        player.addListener(new Player.Listener() {
            @Override
            public void onVideoSizeChanged(VideoSize videoSize) {
                runOnUiThread(() -> {
                    // 设置视频尺寸到 DraggableVideoView
                    videoView.setVideoSize(videoSize.width, videoSize.height);
                });
            }
        });

        // 设置显示区域长按事件，用于重置视频位置
        displayArea.setOnLongClickListener(v -> {
            if (currentMediaItem != null && currentMediaItem.isVideo()) {
                if (videoView != null) {
                    videoView.resetPosition();
                    Toast.makeText(this, "已重置视频位置", Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return false;
        });

        // 设置状态文本点击事件
        statusText.setOnClickListener(v -> {
            if (currentMediaItem != null) {
                onItemClick(currentMediaItem);
            } else if (mediaItems != null && !mediaItems.isEmpty()) {
                onItemClick(mediaItems.get(0));
            }
        });

    }
    private void showLibrarySelector() {
        List<String> librariesList = mediaManager.getAvailableLibraries();
        String[] librariesArray = librariesList.toArray(new String[0]);

        // 使用 BottomSheetDialog
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);

        // 创建 ListView 来显示图库选项
        ListView listView = new ListView(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1, librariesArray);
        listView.setAdapter(adapter);

        // 设置列表项点击事件
        listView.setOnItemClickListener((parent, view, position, id) -> {
            String selectedLibrary = librariesArray[position];
            mediaManager.saveSelectedLibrary(selectedLibrary);
            loadMediaFiles();
            bottomSheetDialog.dismiss();
        });

        // 设置标题
        TextView title = new TextView(this);
        title.setText("选择图库");
        title.setTextSize(18);
        title.setPadding(16, 16, 16, 16);
        title.setBackgroundColor(getResources().getColor(android.R.color.background_light));

        // 创建包含标题和列表的布局
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(title);
        layout.addView(listView);

        // 设置固定高度为300dp
        int heightInPixels = (int) (300 * getResources().getDisplayMetrics().density);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            heightInPixels
        );
        layout.setLayoutParams(layoutParams);

        bottomSheetDialog.setContentView(layout);

        // 调整 BottomSheet 行为
        BottomSheetBehavior<FrameLayout> behavior = bottomSheetDialog.getBehavior();
        behavior.setSkipCollapsed(true); // 跳过折叠状态
        behavior.setHideable(false); // 不可隐藏
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED); // 默认展开

        bottomSheetDialog.show();
    }





    private void initializeLibrarySelector(Spinner spinner) {
        List<String> librariesList = mediaManager.getAvailableLibraries();
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, librariesList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);


        // 设置选择监听器
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedLibrary = (String) parent.getItemAtPosition(position);
                mediaManager.saveSelectedLibrary(selectedLibrary);
                loadMediaFiles();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 处理未选择的情况
            }
        });
    }

    private void adjustDisplayArea() {
        SharedPreferences prefs = getSharedPreferences("display_config", MODE_PRIVATE);
        int topMargin = prefs.getInt("top_margin", AppConfig.DISPLAY_TOP_MARGIN);
        int height = prefs.getInt("height", AppConfig.DISPLAY_HEIGHT);
        int width = prefs.getInt("width", AppConfig.DISPLAY_WIDTH);

        // 如果配置为0，则使用动态计算的值
        if (width == 0) {
            width = getScreenWidth();
        }
        if (height == 0) {
            height = calculateDisplayHeight();
        }

        // 添加有效性检查
        if (height <= 0) height = calculateDisplayHeight();
        if (width <= 0) width = getScreenWidth();
        if (topMargin < 0) topMargin = AppConfig.DISPLAY_TOP_MARGIN;

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) displayArea.getLayoutParams();
        layoutParams.topMargin = topMargin;
        layoutParams.height = height;
        layoutParams.width = width;
        displayArea.setLayoutParams(layoutParams);
    }



    private void saveDisplayConfig() {
        try {
            String topMarginStr = topMarginEdit.getText().toString().trim();
            String heightStr = heightEdit.getText().toString().trim();
            String widthStr = widthEdit.getText().toString().trim();

            // 检查是否为空
            if (topMarginStr.isEmpty() || heightStr.isEmpty() || widthStr.isEmpty()) {
                // 如果有空值，使用默认值而不是直接报错
                Toast.makeText(this, "请输入完整参数", Toast.LENGTH_SHORT).show();
                return;
            }

            int topMargin = Integer.parseInt(topMarginStr);
            int height = Integer.parseInt(heightStr);
            int width = Integer.parseInt(widthStr);

            SharedPreferences prefs = getSharedPreferences("display_config", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("top_margin", topMargin);
            editor.putInt("height", height);
            editor.putInt("width", width);
            editor.apply();

            // 更新显示区域
            adjustDisplayArea();
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效数字", Toast.LENGTH_SHORT).show();
        }
    }


    private void initPlayer() {
        exoPlayer = new ExoPlayer.Builder(this).build();
        videoView.setPlayer(exoPlayer); // 设置播放器到 DraggableVideoView

        exoPlayer.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_READY) {
                    hideLoading();
                } else if (playbackState == Player.STATE_BUFFERING) {
                    showLoading();
                }
            }
        });
    }

    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this,
                        new String[]{
                                Manifest.permission.READ_MEDIA_IMAGES,
                                Manifest.permission.READ_MEDIA_VIDEO
                        },
                        REQUEST_CODE_PERMISSIONS);
            } else {
                loadMediaFiles();
            }
        } else {
            // Android 12 及以下版本
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_PERMISSIONS);
            } else {
                loadMediaFiles();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                loadMediaFiles();
            } else {
                Toast.makeText(this, "需要存储权限才能访问媒体文件", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void loadMediaFiles() {
        showLoading();
        updateStatus("正在扫描媒体文件...");

        new Thread(() -> {
            try {
                // 检查是否有上次选择的图库
                String lastDirectory = mediaManager.getLastSelectedLibrary();
                if (lastDirectory != null && new File(lastDirectory).exists()) {
                    mediaItems = mediaManager.getMediaFilesFromDirectory(lastDirectory);
                } else {
                    mediaItems = mediaManager.getMediaFilesFromDirectory(Environment.getExternalStorageDirectory().getAbsolutePath());
                }

                runOnUiThread(() -> {
                    hideLoading();
                    if (mediaItems.isEmpty()) {
                        showError("未找到媒体文件，请检查存储权限");
                        resetDisplay();
                    } else {
                        setupThumbnailAdapter();
                        updateStatus("找到 " + mediaItems.size() + " 个媒体文件");
                    }
                });
            } catch (Exception e) {
                runOnUiThread(() -> {
                    hideLoading();
                    showError("扫描媒体文件失败: " + e.getMessage());
                    resetDisplay();
                });
            }
        }).start();
    }

    private void setupThumbnailAdapter() {
        thumbnailAdapter = new ThumbnailAdapter(mediaItems);
        thumbnailAdapter.setOnItemClickListener(this);
        thumbnailRecyclerView.setAdapter(thumbnailAdapter);
    }

    @Override
    public void onItemClick(MediaItem2 mediaItem) {
        currentMediaItem = mediaItem;
        if (mediaItem.isVideo()) {
            playVideo(mediaItem);
        } else {
            displayImage(mediaItem);
        }
    }

    private void displayImage(MediaItem2 mediaItem) {
        videoView.setVisibility(View.GONE);
        if (exoPlayer != null) {
            exoPlayer.stop();
        }

        statusText.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
        showLoading();

//        // 设置双击监听
//        imageView.setOnDoubleClickListener(new ZoomableImageView.OnDoubleClickListener() {
//            @Override
//            public void onDoubleClick() {
//                if (imageView.getScale() > 1.0f) {
//                    // 如果已经放大，则重置
//                    imageView.resetZoom();
//                } else {
//                    // 如果未放大，则放大到2倍
//                    // 这里可以添加放大逻辑，或者直接使用现有的缩放功能
//                }
//            }
//        });

        Glide.with(this)
                .load(mediaItem.getFile())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(new com.bumptech.glide.request.target.CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource,
                                                com.bumptech.glide.request.transition.Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        DisplayUtils.adjustImageDisplay(imageView, resource);
                        imageView.fitToWidth();
                        hideLoading();
                        statusText.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadFailed(android.graphics.drawable.Drawable errorDrawable) {
                        hideLoading();
                        showError("图片加载失败: " + mediaItem.getName());
                        statusText.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onLoadCleared(android.graphics.drawable.Drawable placeholder) {
                    }
                });
    }

    private void playVideo(MediaItem2 mediaItem) {
        imageView.setVisibility(View.GONE);
        statusText.setVisibility(View.GONE);
        videoView.setVisibility(View.VISIBLE);
        showLoading();

        try {
            // 设置点击监听器用于暂停/播放 - 直接设置在 videoView 上
            videoView.setOnClickListener(v -> {
                if (exoPlayer != null) {
                    if (exoPlayer.isPlaying()) {
                        exoPlayer.pause();
                        Toast.makeText(this, "已暂停", Toast.LENGTH_SHORT).show();
                    } else {
                        exoPlayer.play();
                        Toast.makeText(this, "继续播放", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            androidx.media3.common.MediaItem videoMediaItem =
                    androidx.media3.common.MediaItem.fromUri(mediaItem.getFile().toURI().toString());
            exoPlayer.setMediaItem(videoMediaItem);
            exoPlayer.prepare();
            exoPlayer.setPlayWhenReady(true);

            // 修改视频尺寸监听部分
            exoPlayer.addListener(new Player.Listener() {
                @Override
                public void onVideoSizeChanged(androidx.media3.common.VideoSize videoSize) {
                    int width = videoSize.width;
                    int height = videoSize.height;

                    if (width > 0 && height > 0) {
                        runOnUiThread(() -> {
                            Log.d("VideoDebug", "Video size: " + width + "x" + height);

                            // 设置视频尺寸
                            videoView.setVideoSize(width, height);

                            // 强制重绘
                            videoView.requestLayout();
                        });
                    }
                }
            });

            hideLoading();
        } catch (Exception e) {
            hideLoading();
            showError("视频播放失败: " + mediaItem.getName());
            statusText.setVisibility(View.VISIBLE);
            Log.e("MainActivity", "视频播放失败", e);
        }
    }



    private void showLoading() {
        loadingIndicator.setVisibility(View.VISIBLE);
    }

    private void hideLoading() {
        loadingIndicator.setVisibility(View.GONE);
    }

    private void updateStatus(String message) {
        statusText.setText(message);
        statusText.setVisibility(View.VISIBLE);
        mainHandler.postDelayed(() -> {
            if (statusText.getVisibility() == View.VISIBLE) {
                statusText.setVisibility(View.GONE);
            }
        }, AppConfig.STATUS_TEXT_DURATION);
    }

    private void showError(String errorMessage) {
        statusText.setText(errorMessage);
        statusText.setVisibility(View.VISIBLE);
        statusText.setBackgroundColor(0x80FF0000);
        Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
    }

    private void resetDisplay() {
        imageView.setVisibility(View.GONE);
        videoView.setVisibility(View.GONE);
        statusText.setVisibility(View.VISIBLE);
        statusText.setText("点击缩略图开始播放");
        statusText.setBackgroundColor(0x80000000);
        if (exoPlayer != null) {
            exoPlayer.stop();
        }
    }

    private int getScreenWidth() {
        return getResources().getDisplayMetrics().widthPixels;
    }

    private int calculateDisplayHeight() {
        return (int) (getScreenWidth() / 1.4);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (exoPlayer != null) {
            exoPlayer.release();
        }
    }

    private static class MaxValueFilter implements android.text.InputFilter {
        private final int max;

        public MaxValueFilter(int max) {
            this.max = max;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   android.text.Spanned dest, int dstart, int dend) {
            try {
                // 构造新值并检查是否超出范围
                String newVal = dest.toString().substring(0, dstart) + source.toString() + dest.toString().substring(dend);
                if (newVal.isEmpty()) return null; // 允许清空

                int input = Integer.parseInt(newVal);
                if (input <= max) {
                    return null; // 接受输入
                }
            } catch (NumberFormatException ignored) {}

            // 拒绝输入
            return "";
        }
    }


}